package com.gaohe.web.controller.dcp;

import com.gaohe.common.annotation.Log;
import com.gaohe.common.core.controller.BaseController;
import com.gaohe.common.core.domain.AjaxResult;
import com.gaohe.common.core.domain.entity.SysUser;
import com.gaohe.common.core.domain.model.LoginUser;
import com.gaohe.common.core.page.TableDataInfo;
import com.gaohe.common.enums.BusinessType;
import com.gaohe.common.utils.SecurityUtils;
import com.gaohe.common.utils.poi.ExcelUtil;
import com.gaohe.dcp.domain.DcpScheduling;
import com.gaohe.dcp.service.IDcpSchedulingService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 排班记录Controller
 *
 * @author ruoyi
 * @date 2025-04-23
 */
@RestController
@RequestMapping("/dcp/scheduling")
public class DcpSchedulingController extends BaseController
{
    @Autowired
    private IDcpSchedulingService dcpSchedulingService;

    /**
     * 查询排班记录列表
     */
    @PreAuthorize("@ss.hasPermi('dcp:scheduling:list')")
    @GetMapping("/list")
    public TableDataInfo list(DcpScheduling dcpScheduling)
    {
//        startPage();
//        List<DcpScheduling> list = dcpSchedulingService.selectDcpSchedulingList(dcpScheduling);
//        return getDataTable(list);
        // 获取当前登录用户
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        System.err.println(user.getDeptId()+"111111111111");

        // 根据角色设置查询条件
        if (!SecurityUtils.isAdmin(user.getUserId()))
        {
            // 检查是否为医院负责人（部门管理员）
            if (user.getRoles().stream().anyMatch(r -> "director".equals(r.getRoleKey())))
            {
                // 医院负责人只能查看本部门的排班
//                dcpScheduling.setDeptId(user.getDeptId());
            }
            else
            {
                // 普通医生只能查看自己的排班
                dcpScheduling.setUserId(user.getUserId());
            }
        }

        startPage();
        List<DcpScheduling> list = dcpSchedulingService.selectDcpSchedulingList(dcpScheduling);
        return getDataTable(list);
    }

    /**
     * 导出排班记录列表
     */
    @PreAuthorize("@ss.hasPermi('dcp:scheduling:export')")
    @Log(title = "排班记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DcpScheduling dcpScheduling)
    {
        List<DcpScheduling> list = dcpSchedulingService.selectDcpSchedulingList(dcpScheduling);
        ExcelUtil<DcpScheduling> util = new ExcelUtil<DcpScheduling>(DcpScheduling.class);
        util.exportExcel(response, list, "排班记录数据");
    }

    /**
     * 获取排班记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('dcp:scheduling:query')")
    @GetMapping(value = "/{schedulingId}")
    public AjaxResult getInfo(@PathVariable("schedulingId") Long schedulingId)
    {
//        return success(dcpSchedulingService.selectDcpSchedulingBySchedulingId(schedulingId));
        DcpScheduling scheduling = dcpSchedulingService.selectDcpSchedulingBySchedulingId(schedulingId);

        // 获取当前登录用户
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();

        // 根据角色进行权限控制
        if (!SecurityUtils.isAdmin(user.getUserId()))
        {
            // 检查是否为医院负责人（部门管理员）
            if (user.getRoles().stream().anyMatch(r -> "director".equals(r.getRoleKey())))
            {
                // 医院负责人只能查看本部门的排班
//                if (!user.getDeptId().equals(scheduling.getDeptId()))
//                {
//                    return error("无权查看其他部门的排班信息");
//                }
            }
            else
            {
                // 普通医生只能查看自己的排班
                if (!user.getUserId().equals(scheduling.getUserId()))
                {
                    return error("无权查看其他医生的排班信息");
                }
            }
        }

        return success(scheduling);
    }

    /**
     * 新增排班记录
     */
    @PreAuthorize("@ss.hasPermi('dcp:scheduling:add')")
    @Log(title = "排班记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DcpScheduling dcpScheduling)
    {
//        System.err.println(dcpScheduling);
//        return toAjax(dcpSchedulingService.insertDcpScheduling(dcpScheduling));
        // 获取当前登录用户
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();

        // 根据角色进行权限控制
        if (!SecurityUtils.isAdmin(user.getUserId()))
        {
            // 检查是否为医院负责人（部门管理员）
            if (user.getRoles().stream().anyMatch(r -> "director".equals(r.getRoleKey())))
            {
                // 医院负责人只能为本部门添加排班
//                dcpScheduling.setDeptId(user.getDeptId());
//                dcpScheduling.setUserName(user.getNickName());
                // 如果尝试为其他部门的医生排班，则拒绝
                if (dcpScheduling.getUserId() != null && !dcpSchedulingService.checkUserInDept(dcpScheduling.getUserId(), user.getDeptId()))
                {
                    return error("无权为其他部门的医生排班");
                }
            }
            else
            {
                // 普通医生不能添加排班
                return error("无权添加排班信息");
            }
        }
        System.err.println("数据："+dcpScheduling);
        return toAjax(dcpSchedulingService.insertDcpScheduling(dcpScheduling));
    }

    /**
     * 修改排班记录
     */
    @PreAuthorize("@ss.hasPermi('dcp:scheduling:edit')")
    @Log(title = "排班记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DcpScheduling dcpScheduling)
    {
        return toAjax(dcpSchedulingService.updateDcpScheduling(dcpScheduling));
    }

    /**
     * 删除排班记录
     */
    @PreAuthorize("@ss.hasPermi('dcp:scheduling:remove')")
    @Log(title = "排班记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{schedulingIds}")
    public AjaxResult remove(@PathVariable Long[] schedulingIds)
    {
        return toAjax(dcpSchedulingService.deleteDcpSchedulingBySchedulingIds(schedulingIds));
    }

    /**
     * 根据医生名称查询排班信息
     */
    @PreAuthorize("@ss.hasPermi('dcp:scheduling:list')")
    @GetMapping("/doctor/{doctorName}")
    public AjaxResult getSchedulingByDoctorName(@PathVariable("doctorName") String doctorName)
    {
        DcpScheduling dcpScheduling = new DcpScheduling();
        dcpScheduling.setUserName(doctorName);
        System.err.println("-----------------------------------------");
        System.err.println(doctorName);
        List<DcpScheduling> list = dcpSchedulingService.selectDcpSchedulingList(dcpScheduling);
        System.err.println("-----------------------------------------2");
        System.err.println(list);
        return success(list);
    }

    /**
     * 查询本周排班信息
     */
    @PreAuthorize("@ss.hasPermi('dcp:scheduling:list')")
    @GetMapping("/week")
    public AjaxResult getWeekScheduling(DcpScheduling dcpScheduling)
    {
        List<DcpScheduling> list = dcpSchedulingService.selectDcpSchedulingList(dcpScheduling);
        return success(list);
    }
}
